﻿//用户服务，登录充值
"use strict";
const mvc         = require("cosjs.mvc");
const body        = require('body-parser');
const notify      = '/order/notify';

module.exports = function(){
    let app = this;
    app.defineHandlePrototype("model",mvc.model);
    app.defineHandlePrototype("config",mvc.config);
    app.defineHandlePrototype("library",mvc.library);
    /////////////////////远程跨域//////////////////////
    app.use(function (req,res,next) { res.set("Access-Control-Allow-Origin","*"); next();})
    /////////////////////ping//////////////////////
    app.use('/ping',function (req,res,next) {
        res.end(String(Date.now()));
    })
    create_server.call(app);
};

module.exports.create = create_server;

/////////////////////用户登录服务//////////////////////
function create_server(){
    // var stack = new Error().stack
    // console.log( stack )
    let app = this;
    let root = mvc.config.get("root");
    let route = "/:branch/:opensdk/*";
    if(arguments[0]){
        route = `/${arguments[0]}${route}`;
    }
    //gzip压缩
    //apps.use(compression());
    let urlencoded  = body.urlencoded({ extended: true,limit:"100kb" });
    let jsonencoded = body.json({extended: true,limit:"100kb", });
    let textencoded = body.text({ type:"*/xml",limit:"100kb"});
    //远程服务
    let service_root = root + '/handle/service';
    let service_route = {route:route,method:'all',output:'json',subpath:handle_service_subpath}
    // console.log("service_root :",service_root)
    // console.log("service_route :",service_route)
    let service_server = app.server(service_root,service_route,urlencoded,jsonencoded,textencoded);
    service_server.on('start',handle_service_start);
    service_server.on('finish', handle_service_finish);
}


function handle_service_subpath(){
    let path = this.req.params[0];
    console.log("path ------------",path)
    if(path[0] !== '/'){
        path = '/' + path;
    }
    //充值回调,防止脑残平台没有透传参数，URL也不让带参数
    let attach_notify = [notify,'/'].join('');
    if(path.substr(0,attach_notify.length) == attach_notify){
        let attachStr = path.substr(attach_notify.length );
        let attachArr = attachStr.split('|');
        if(attachArr.length >= 3){
            this.req.params['attach'] = attachStr;
        }
        path = notify;
    }
    //返回service path
    return path;
}

async function handle_service_start(){
    let branch = this.req.params['branch'];
    let opensdk = this.req.params['opensdk'];
    if( !branch || !opensdk ){
        return this.error('error','args[branch||opensdk] empty');
    }
    let keys = ["_id","key","cyt","o2g","status",'payment',"branch","iptable","ipblock","setting","version"];
    this.opensdkModel = this.model.branch('opensdk',branch);
    let ret=await this.opensdkModel.get(opensdk,keys);
    if(!ret){
        return this.error('opensdk_not_exist',opensdk);
    }
    if(ret['status']>1){
        return this.error('opensdk_disabled',opensdk);
    }
    this.branch = branch;
    this.opensdk = ret;
    if(ret['key']=='develop'){
          this.isDev=true;
    }else{
        this.isDev=false;
    }
    if(ret["iptable"]){
        await iptable_verify.call(this);
    }
    if(ret["ipblock"]){
        await ipblock_verify.call(this);
    }
}

function handle_service_finish(err,ret){
    return {err:err,ret:ret,time:Date.now()};
}

function iptable_verify(){
    let ip = this.req.ip;
    let iptable = this.model.branch("iptable",this.branch);
    return iptable.verify(ip).then(ret=>{
        if(!ret){
//            console.log("不在IP白名单");
            return this.error("server_iptable_limit",ip);
        }
    })
}

function ipblock_verify(){
    let ip = this.req.ip;
    let iptable = this.model.branch("ipblock",this.branch);
    return iptable.verify(ip).then(ret=>{
        if(ret){
           // console.log("你在IP黑名单");
            return this.error("server_block_limit",ip);
        }
    })
}